package LinkedList;

public class 移除链表元素 {
    public ListNode removeElements(ListNode head, int val) {
        // 添加虚节点方式
        /*if (head == null) return head;
        // 因为删除可能涉及到头节点，所以设置dummy节点，统一操作
        ListNode dummy = new ListNode(-1, head);
        ListNode pre = dummy;
        ListNode cur = head;
        while (cur != null) {
            if (cur.val == val) pre.next = cur.next;
            else pre = cur;
            cur = cur.next;
        }
        return dummy.next;*/

        // 不添加虚拟节点方式
        /*while (head != null && head.val == val) head = head.next;
        // 已经为null，提前退出
        if (head == null) return head;
        // 已确定当前head.val != val
        ListNode pre = head;
        ListNode cur = head.next;
        while (cur != null) {
            if (cur.val == val) pre.next = cur.next;
            else pre = cur;
            cur = cur.next;
        }
        return head;*/

        // 不添加虚拟节点与pre节点方式
        while (head != null && head.val == val) head = head.next;
        ListNode curr = head;
        while (curr != null) {
            while (curr.next != null && curr.next.val == val) curr.next = curr.next.next;
            curr = curr.next;
        }
        return head;
    }
}
